package red.internal.server.registry.handler;

import io.netty.channel.Channel;
import red.internal.core.handler.SenderListener;
import red.internal.core.message.RegistryMessage;
import red.internal.server.exception.RegistryStorageException;
import red.internal.server.registry.storage.RegistryStorage;


/**
 * @author Jin Zheng
 * @since 1.0 2019-05-10
 */
public class SaveRegistryHandler implements RegistryHandler
{
	private final RegistryStorage storage;

	public SaveRegistryHandler(RegistryStorage storage)
	{
		this.storage = storage;
	}

	@Override
	public void handle(RegistryMessage message, Channel channel)
	{
		if (message.getNameSet().isEmpty())
			throw new RegistryStorageException("name is empty");

		storage.save(message.getNameSet(), channel);
		RegistryMessage response = message.success();
		channel.writeAndFlush(response).addListener(new SenderListener(response));
	}

}
